<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        window.onload = function () {
            var adiv = document.querySelector('#div')
            var num1 = 10;//字符数
            var str = 5;//干扰数量
            adiv.onclick = function (event) {
                console.log('执行')
                this.innerHTML = `<canvas style="border: 1px dashed black;" width="150px" height="50px"></canvas>`;
                var cans = document.querySelector('canvas')  //获取目标canvas元素对象 //获取2d画笔
                var can = cans.getContext('2d');
                for (var n = 1; n <= str; n++) {
                    var color = ` rgb(${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)})`;
                    can.beginPath();
                    can.moveTo(parseInt(Math.random() * 151), parseInt(Math.random() * 51));  //确定线条起点
                    can.lineTo(parseInt(Math.random() * 151), parseInt(Math.random() * 50));  //绘制线条到指定点
                    can.closePath();
                    can.strokeStyle = color;  //设置线条颜色
                    can.lineWidth = parseInt(Math.random() * 10);  //设置线条的宽度
                    can.stroke();  //呈现线条
                }
                var  wid = parseInt(150 / num1),s = 0;
                function demo(){
                    var str = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUPASDFGHJKLZXCVBNM';
                    return str.charAt(parseInt(Math.random() * str.length))
                }
                for (var n1 = 1; n1 <= num1; n1++) {
                    
                    can.beginPath();
                    var sixe=parseInt(Math.random()*20+10)
                    can.font = `bold ${sixe}px 楷体`;
                    var d=demo()
                    var y=parseInt(Math.random() * (51-sixe)+sixe)
                    console.log(d)
                    var color = ` rgb(${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)})`;
                    can.fillStyle=color
                    can.fillText(`${d}`, s, y)
                    can.closePath();
                    s+=wid
                }
            }
        }


    </script>
</head>

<body>
    <div id="div">
        <canvas style="border: 1px dashed black;" width="150px" height="50px">

        </canvas>
    </div>
</body>

</html>